﻿using System;
using System.Threading.Tasks;
using System.Transactions;
using HengTong.Model.Db.Hr.Bill;
using TiaoTaoHelper.Wtm.Models;
using TiaoTaoHelper.Wtm.Workflow;


namespace HengTong.ViewModel.Person.SysPersonRepairBillVms
{
    public partial class SysPersonRepairBillVm : CrudVm<SysPersonRepairBill>
    {
        public SysPersonRepairBillVm()
        {
            SetInclude(x => x.Org);
            SetInclude(x => x.Group);
            SetInclude(x => x.JobPosition);
            SetInclude(x => x.PersonEducations);
            SetInclude(x => x.PersonFamilies);
            SetInclude(x => x.PersonWorks);
            SetInclude(x => x.PersonTrainExams);
            SetInclude(x => x.PersonMedicals);
            SetInclude(x => x.PersonResumes);
            SetInclude(x => x.PersonContracts);
        }

        protected override void InitVM()
        {
            base.InitVM();
        }

        /// <summary>
        /// 必须使用异步事务, 否则工作流引擎会和当前事务冲突
        /// </summary>
        /// <param name="upAllFields"></param>
        public async Task ApproveAsync(bool upAllFields = false)
        {
            using var transactionScope = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromMinutes(10) // 增加超时时间到10分钟
                },
                TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                if (Entity.BillStatus == BillStatus.草稿) Entity.BillStatus = BillStatus.正文;
                Entity.Approver = Wtm.LoginUserInfo?.ITCode;
                Entity.ApprovalTime = DateTime.Now;
                await base.DoEditAsync(upAllFields);
                if (MSD.IsValid)
                {
                    var result = await ContinueWorkflowAsync(ActionName, Remark, "档案补录流程");
                    if (result.Executed == true)
                    {
                        transactionScope.Complete(); // 提交事务
                    }
                    else
                    {
                        MSD.AddModelError(" ", $"工作流执行失败");
                    }
                }
                // 如果到这里，事务会自动回滚
            }
            catch (Exception e)
            {
                // TransactionScope会自动回滚，无需手动操作
                MSD.AddModelError(" ", $"审批操作异常: {e.Message}");
            }
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }
    }
}